<template>
  <n-upload
    action="api/upload"
    :default-file-list="previewFileList"
    :max="max"
    list-type="image-card"
    accept="image/*"
    response-type="json"
    @preview="handlePreview"
    @finish="handleFinish"
    @remove="handleChange"
  >
    <img v-if="defaultImage" style="width: 100%;max-height: 100%;" :src="defaultImage">
  </n-upload>
  <n-modal
    v-model:show="showModal"
    preset="card"
    style="width: 600px"
    title="预览图"
  >
    <img :src="previewImageUrl" style="width: 100%">
  </n-modal>
</template>

<script setup lang='ts'>
  import { ref,onMounted,inject } from 'vue'
  import { UploadFileInfo } from 'naive-ui'

  const host = ref(inject("host"))

  defineProps<{
    max:number,
    defaultImage?: string,
  }>()

  const emits = defineEmits<{
    changeImageList: [fileList: Array<UploadFileInfo>]
  }>()

  const token = ref("")
  let showModal = ref(false)
  let previewImageUrl = ref()
  const previewFileList = ref<UploadFileInfo[]>([])

  // 点击预览函数
  const handlePreview = async (file: UploadFileInfo) => {
    const {url} = file
    previewImageUrl.value = url
    showModal.value = true
  }
  // 上传成功回调
  const handleFinish =(options: { file: UploadFileInfo, event?: ProgressEvent}) => {
    options.file.url = host.value + "/api/" + (options.event?.target as XMLHttpRequest).response?.url
    previewFileList.value.push(options.file)
    let fileList = previewFileList.value.map(e => {
        return{
          ...e,
          url: e.url?.split("api/")[1]
        }
      }
    )
    emits("changeImageList", fileList)
  }
  // 删除图片回调
  const handleChange = (options: { file: UploadFileInfo, fileList: Array<UploadFileInfo> }) => {
    previewFileList.value = previewFileList.value.filter(e => e.batchId!=options.file.batchId)
    let fileList = previewFileList.value.map(e => {
        return{
          ...e,
          url: e.url?.split("api/")[1]
        }
      }
    )
    emits("changeImageList", fileList)
  }
  
  onMounted(() => {
    token.value = localStorage.getItem("jwt") as string
  })
</script>

<style lang='scss' scoped>
  
</style>